package com.leetcode.LC_MED;

import java.util.LinkedList;
import java.util.Queue;

public class LC938 {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if (root == null) {
            return 0;
        }
        int rs = 0;
        int leftSum = rangeSumBST(root.left, L, R);
        int rightSum = rangeSumBST(root.right, L, R);
        rs = leftSum + rightSum;
        if (root.val >= L && root.val <= R) {
            rs += root.val;
        }
        return rs;
    }

    public int rangeSumBST2(TreeNode root, int low, int high) {
        if (root == null) {
            return 0;
        }

        int rs = 0;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (queue.size() > 0) {
            int size = queue.size();
            while (size > 0) {
                TreeNode poll = queue.poll();
                if (poll.val >= low && poll.val <= high) {
                    rs += poll.val;
                }
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
                size--;
            }
        }
        return rs;
    }
}
